package cn.sightsnow.zh.service;

import cn.sightsnow.zh.entity.Route;
import cn.sightsnow.zh.repository.RouteRepository;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class RouteService {

    private final RouteRepository routeRepository;

    public RouteService(RouteRepository routeRepository) {
        this.routeRepository = routeRepository;
    }

    public List<Route> findRoutesByStatus(Integer status) {
        if (status != null) {
            return routeRepository.findByStatus(status);
        }
        return routeRepository.findAll();
    }


    public void deleteRoute(String routeId) {
        routeRepository.deleteById(routeId);
    }

    public Optional<Route> getRouteById(String routeId) {
        return routeRepository.findById(routeId);
    }


    public Route createRoute(Route route) {
        // 自动生成ID（如果前端没传）
        if (!StringUtils.hasText(route.getRouteId())) {
            route.setRouteId(new ObjectId().toString());
        }
        // 自动设置开始时间
        route.setStartTime(LocalDateTime.now());
        return routeRepository.save(route);
    }

    public Route updateRoute(Route route) {
        Route existing = routeRepository.findById(route.getRouteId())
                .orElseThrow(() -> new RuntimeException("路径不存在"));
        existing.setStartPoint(route.getStartPoint());
        existing.setEndPoint(route.getEndPoint());
        existing.setStartTime(route.getStartTime());
        // 当设置结束时间时自动更新状态
        if (route.getEndTime() != null) {
            existing.setEndTime(route.getEndTime());
            existing.setStatus(0);
        }
        return routeRepository.save(existing);
    }


    // 新增存在性检查
    public boolean existsById(String routeId) {
        return routeRepository.existsById(routeId);
    }





}
